import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Button, Row, Col } from 'antd';
import { connect, Dispatch, history } from 'umi';
import PdfViewer from '@/components/PdfViewer';
import ProjectLayout from './ProjectLayout';

import { StateType } from './model';

import styles from './index.less';

interface BasicProps {
  match: any;
  project: StateType;
  dispatch: Dispatch;
  loading: boolean;
}

interface BasicState {
  mPage: number;
  oPage: number;
  mRef: any;
  oRef: any;
  scale: number;
  singleDraw: boolean;
}

class ProjectDetail extends Component<BasicProps, BasicState> {
  state: BasicState = {
    mPage: 0,
    oPage: 0,
    mRef: null,
    oRef: null,
    scale: 1,
    singleDraw: true,
  };

  componentDidMount() {
    const {
      dispatch,
      match: {
        params: { id },
      },
    } = this.props;
    dispatch({
      type: 'project/fetch',
      payload: id,
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'project/clear',
    });
  }

  handlePdfViewerPropsChange = (url: string, marks: any[]) => {
    this.handlePropsChange({
      payload: {
        drawingUrl: url,
        drawingMarks: marks,
      },
    });
  };

  handlePdfSelect = (url?: string) => {
    this.handlePdfViewerPropsChange(url || '', []);
  };

  handleDrawComplete = (params: any) => {
    const { singleDraw } = this.state;
    const {
      project: { drawingMarks },
    } = this.props;
    if (singleDraw) {
      drawingMarks.length = 0;
    }
    drawingMarks.push({ data: JSON.stringify(params) });
    this.handlePropsChange({
      drawingMarks,
      collapsed: false,
    });
  };

  handleSetMRef = (ref: any) => {
    this.setState({
      mRef: ref,
    });
  };

  handleSetORef = (ref: any) => {
    this.setState({
      oRef: ref,
    });
  };

  handleScroll = (left: number, top: number) => {
    const { mRef, oRef } = this.state;
    if (mRef) {
      mRef.scrollLeft = left;
      mRef.scrollTop = top;
    }
    if (oRef) {
      oRef.scrollLeft = left;
      oRef.scrollTop = top;
    }
  };

  handleZoom = (scale: number) => {
    this.setState({
      scale,
    });
  };

  handlePageChange = (current: number) => {
    this.setState({
      oPage: current,
      mPage: current,
    });
  };

  handlePropsChange = (val: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'project/save',
      payload: val,
    });
  };

  handleSaveIssue = (
    payload: { bhid?: string; opinion?: string; marks?: any },
    callback: (success: boolean) => void,
  ) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'project/addIssue',
      payload,
      callback: (success: boolean) => {
        if (callback) {
          callback(success);
        }
      },
    });
  };

  render() {
    const { singleDraw, scale, oPage, mPage } = this.state;
    const { project } = this.props;
    const {
      unitProject,
      pdfMarkable,
      drawingUrl,
      drawingMarks,
      compareList,
      compareMarks,
    } = project;
    const { name } = unitProject || {};
    return (
      <PageHeaderWrapper
        className={styles.pageHeaderWrapper}
        title={`${name}`}
        extra={
          <Button
            type="primary"
            onClick={() => {
              history.goBack();
            }}
          >
            返回
          </Button>
        }
      >
        <ProjectLayout
          onPropsChange={this.handlePropsChange}
          onIssueSelect={this.handlePdfViewerPropsChange}
          onSaveIssue={this.handleSaveIssue}
          onPdfSelect={this.handlePdfSelect}
          data={project}
        >
          <Card style={{ height: '100%' }} bodyStyle={{ padding: 0 }}>
            {compareList.length < 2 && (
              <PdfViewer
                singleDraw={singleDraw}
                canvasDivHeight={window.innerHeight - 224}
                url={drawingUrl}
                marks={drawingMarks}
                markable={pdfMarkable}
                onDrawComplete={this.handleDrawComplete}
                onPdfLoading={() => {
                  this.handlePropsChange({ pdfLoading: true });
                }}
                onPdfLoadingSuccess={() => {
                  this.handlePropsChange({ pdfLoading: false });
                }}
              />
            )}
            {compareList.length === 2 && (
              <Row gutter={16}>
                <Col span={12}>
                  <PdfViewer
                    scale={scale}
                    setRef={this.handleSetORef}
                    page={oPage}
                    canvasDivHeight={window.innerHeight - 224}
                    url={compareList[1].url}
                    marks={compareMarks[1]}
                    markable={false}
                    onDrawComplete={this.handleDrawComplete}
                    onScroll={this.handleScroll}
                    onZoom={this.handleZoom}
                    onPageChange={this.handlePageChange}
                    onPdfLoading={() => {
                      this.handlePropsChange({ oPdfLoading: true });
                    }}
                    onPdfLoadingSuccess={() => {
                      this.handlePropsChange({ oPdfLoading: false });
                    }}
                  />
                </Col>
                <Col span={12}>
                  <PdfViewer
                    scale={scale}
                    setRef={this.handleSetMRef}
                    page={mPage}
                    canvasDivHeight={window.innerHeight - 224}
                    url={compareList[0].url}
                    marks={compareMarks[0]}
                    markable={false}
                    onDrawComplete={this.handleDrawComplete}
                    onScroll={this.handleScroll}
                    onZoom={this.handleZoom}
                    onPageChange={this.handlePageChange}
                    onPdfLoading={() => {
                      this.handlePropsChange({ mPdfLoading: true });
                    }}
                    onPdfLoadingSuccess={() => {
                      this.handlePropsChange({ mPdfLoading: false });
                    }}
                  />
                </Col>
              </Row>
            )}
          </Card>
        </ProjectLayout>
      </PageHeaderWrapper>
    );
  }
}

export default connect(
  ({
    project,
    loading,
  }: {
    project: StateType;
    loading: {
      models: { [key: string]: boolean };
    };
  }) => ({
    project,
    loading: loading.models.project,
  }),
)(ProjectDetail);
